<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>语音合成和语音识别</title>
  </head>
  <body>
    <input class="inp" type="text" />
    <button class="btn">听</button>

    <hr />

    <button class="btn2">开启语言识别</button>
    <textarea class="inp2" name="" id="" cols="30" rows="10"></textarea>
  </body>
  <script>
    // 语音合成
    const inp = document.querySelector(".inp");
    const btn = document.querySelector(".btn");
    let spk = new window.SpeechSynthesisUtterance();
    // 语言类型
    spk.lang = "zh-CN";
    // 音高
    spk.pitch = 20;
    // 说话的速度
    spk.rate = 1;
    btn.onclick = function () {
      // 要说的话
      spk.text = inp.value;
      window.speechSynthesis.speak(spk);
    };

    // 语音识别
    const inp2 = document.querySelector(".inp2");
    const btn2 = document.querySelector(".btn2");

    let SpeechRecognition = new webkitSpeechRecognition();
    console.log(SpeechRecognition);
    // 配置是一直识别还是识别到声音就关闭
    SpeechRecognition.continuous = true;
    // 配置语言
    // SpeechRecognition.lang = "en-US";
    let state = 1;
    btn2.onclick = function () {
      if (state == 1) {
        btn2.innerHTML = "关闭语音识别";
        SpeechRecognition.start();
        state++;
        console.log(inp2.value);
        // 接收到可以识别的语音时触发,可以触发多次
        SpeechRecognition.onresult = function (e) {
          inp2.value += e.results[e.results.length - 1][0].transcript;
        };
      } else {
        btn2.innerHTML = "开启语音识别";
        SpeechRecognition.stop();
        state = 1;
      }
    };
  </script>
</html>
